<?php
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台欢迎页
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\controller\Adminbase;
use app\Constant\OrderConstant;
use app\model\Order;
use app\model\User;
use libs\Redis;
use think\Db;

class Main extends Adminbase
{
    /*
     * 系统首页
     */
    public function index()
    {
        $redis = extension_loaded('redis') ? Redis::getRedis() : null;
        if ($redis) {
            $users_count = $redis->get(config('redis_keys')['users_count']);
            if ($users_count) {
                $users_count = json_decode($users_count, true);
            } else {
                [$users_count] = $this->count($redis);
            }
        } else {
            [$users_count] = $this->count($redis);
        }

        $this->assign('users_count', $users_count);
        $this->assign('userInfo', $this->_userinfo);
        $this->assign('sys_info', $this->get_sys_info());
        return $this->fetch();
    }

    /*
     * 代理商首页
     */
    public function agent()
    {
        $this->assign('users_count', []);
        return $this->fetch();
    }

    /**
     * 首页统计
     * @param $redis
     * @return array[]
     */
    public function count($redis)
    {
        $time  = time();
        $year  = date('Y', $time);
        $month = date('n', $time);
        $day   = date('j', $time);
        //用户统计
        $user_total  = User::where('status', 1)->count();
        $day_total   = User::where('status', 1)->where('day', $day)->count();
        $month_total = User::where('status', 1)->where('month', $month)->count();
        $year_total  = User::where('status', 1)->where('year', $year)->count();
        $users_count = [
            'total' => $user_total,
            'day'   => $day_total,
            'month' => $month_total,
            'year'  => $year_total,
        ];

        if ($redis) {
            $redis->setex(config('redis_keys')['users_count'], 3600, json_encode($users_count));
        }
        return [$users_count];
    }

    /**
     * 折线图数据
     * @return \think\response\Json
     */
    public function data()
    {
        $type       = $this->request->param('type');
        $date_range = $this->request->param('date');
        $start      = $end = 0;

        if ($date_range) {
            $date_range = explode(' - ', $date_range);
            $date       = $start = strtotime($date_range[0]);
            $end        = strtotime($date_range[1]  . ' 23:59:59');
            do {
                $days[] = date('Y-m-d', $date);
                $date   = strtotime('+1 day', $date);
            } while ($date <= $end);
        } else {
            $recent_days = getRecentDays();
            $start       = strtotime($recent_days[0]['value']);
            $end         = strtotime($recent_days[count($recent_days) - 1]['value'] . ' 23:59:59');
            $days        = array_column($recent_days, 'value');
        }
        $data = [];
        switch ($type) {
            case 'order':
                $orders     = Order::field('id, status, create_time')
                    ->withAttr('create_time', function ($value) {
                        return date('Y-m-d', $value);
                    })
                    ->whereIn('status', [OrderConstant::ORDER_STATUS_PENDING_PAYMENT, OrderConstant::ORDER_STATUS_COMPLETED, OrderConstant::ORDER_STATUS_CANCELLED])
                    ->whereBetween('create_time', [$start, $end])->select();
                $date_order = [];
                foreach ($orders as $item) {
                    $date_order[$item['create_time']][] = $item;
                }
                $total = $pending = $paid = $canceled = [];
                foreach ($days as $day) {
                    $day_total = $day_pending = $day_paid = $day_canceled = 0;
                    $order     = $date_order[$day] ?? [];
                    if ($order) {
                        $day_total = count($order);
                        foreach ($order as $item) {
                            switch ($item['status']) {
                                case OrderConstant::ORDER_STATUS_PENDING_PAYMENT:
                                    $day_pending++;
                                    break;
                                case OrderConstant::ORDER_STATUS_COMPLETED:
                                    $day_paid++;
                                    break;
                                case OrderConstant::ORDER_STATUS_CANCELLED:
                                    $day_canceled++;
                                    break;
                            }
                        }
                    }
                    $total[]    = $day_total;
                    $pending[]  = $day_pending;
                    $paid[]     = $day_paid;
                    $canceled[] = $day_canceled;
                }


                $data = [
                    'total'    => $total,
                    'pending'  => $pending,
                    'paid'     => $paid,
                    'canceled' => $canceled
                ];
                break;
            case 'user':
                $users     = User::field('id, create_time')
                    ->withAttr('create_time', function ($value) {
                        return date('Y-m-d', $value);
                    })
                    ->where('status', 1)
                    ->whereBetween('create_time', [$start, $end])->select();
                $date_user = [];
                foreach ($users as $item) {
                    $date_user[$item['create_time']][] = $item;
                }
                $total = [];
                foreach ($days as $day) {
                    $user    = $date_user[$day] ?? [];
                    $total[] = count($user);
                }
                $data = [
                    'total' => $total
                ];
        }
        return json(['code' => 0, 'data' => $data, 'xAxis' => $days]);
    }

    //phpinfo信息 按需显示在前台
    public function get_sys_info()
    {
        $sys_info['os']            = PHP_OS; //操作系统
        $sys_info['ip']            = GetHostByName($_SERVER['SERVER_NAME']); //服务器IP
        $sys_info['web_server']    = $_SERVER['SERVER_SOFTWARE']; //服务器环境
        $sys_info['phpv']          = phpversion(); //php版本
        $sys_info['fileupload']    = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknown'; //文件上传限制
        $sys_info['domain']        = $_SERVER['HTTP_HOST']; //域名
        $sys_info['beijing_time']  = gmdate("Y年n月j日 H:i:s", time() + 8 * 3600); //北京时间
        $mysqlinfo                 = Db::query("SELECT VERSION() as version");
        $sys_info['mysql_version'] = $mysqlinfo[0]['version'];
        if (function_exists("gd_info")) {
            //GD库版本
            $gd                 = gd_info();
            $sys_info['gdinfo'] = $gd['GD Version'];
        } else {
            $sys_info['gdinfo'] = "未知";
        }
        return $sys_info;
    }

}
